package cn.ch.train.business.service;

import cn.ch.train.business.domain.TrainCarriage;
import cn.ch.train.business.domain.TrainCarriageExample;
import cn.ch.train.business.enums.BusinessExceptionEnum;
import cn.ch.train.business.enums.SeatColEnum;
import cn.ch.train.business.mapper.TrainCarriageMapper;
import cn.ch.train.business.request.TrainCarriageQueryParam;
import cn.ch.train.business.request.TrainCarriageSaveParam;
import cn.ch.train.business.response.TrainCarriageQueryResult;
import cn.ch.train.common.exception.BusinessException;
import cn.ch.train.common.response.PageResult;
import cn.ch.train.common.util.SnowUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class TrainCarriageService {
    private static final Logger logger = LoggerFactory.getLogger(TrainCarriageService.class);
    @Resource
    private TrainCarriageMapper trainCarriageMapper;

    public void save(TrainCarriageSaveParam param) {
        DateTime now = DateTime.now();
        // 自动计算出列数和总座位数
        List<SeatColEnum> seatColEnumList = SeatColEnum.getColsByType(param.getSeatType());
        param.setColCount(seatColEnumList.size());
        param.setSeatCount(param.getColCount() * param.getRowCount());

        TrainCarriage trainCarriage = BeanUtil.copyProperties(param, TrainCarriage.class);
        // 保存之前，先校验唯一键是否存在
        TrainCarriage trainCarriageDb = selectByUnique(param.getTrainCode(), param.getIndex());
        if (Objects.nonNull(trainCarriageDb)) {
            throw new BusinessException(BusinessExceptionEnum.STATION_HAS_EXIST.getDesc());
        }
        if (Objects.isNull(trainCarriage.getId())) {
            trainCarriage.setId(SnowUtil.getSnowFlakeNextId());
            trainCarriage.setCreateTime(now);
            trainCarriage.setUpdateTime(now);
            trainCarriageMapper.insert(trainCarriage);
        } else {
            trainCarriage.setUpdateTime(now);
            trainCarriageMapper.updateByPrimaryKey(trainCarriage);
        }
    }

    private TrainCarriage selectByUnique(String trainCode, Integer index) {
        TrainCarriageExample stationExample = new TrainCarriageExample();
        TrainCarriageExample.Criteria criteria = stationExample.createCriteria();
        criteria.andTrainCodeEqualTo(trainCode);
        criteria.andIndexEqualTo(index);
        List<TrainCarriage> stationList = trainCarriageMapper.selectByExample(stationExample);
        if (CollUtil.isNotEmpty(stationList)) {
            return stationList.get(0);
        }
        return null;
    }

    public PageResult<TrainCarriageQueryResult> queryList(TrainCarriageQueryParam param) {
        TrainCarriageExample trainCarriageExample = new TrainCarriageExample();
        trainCarriageExample.setOrderByClause("train_code asc, `index` asc");
        TrainCarriageExample.Criteria criteria = trainCarriageExample.createCriteria();
        PageHelper.startPage(param.getPageNo(), param.getPageSize());
        List<TrainCarriage> trainCarriageList = trainCarriageMapper.selectByExample(trainCarriageExample);

        PageInfo<TrainCarriage> trainCarriagePageInfo = new PageInfo<>(trainCarriageList);
        logger.info("总行数：{}", trainCarriagePageInfo.getTotal());
        logger.info("总页数：{}", trainCarriagePageInfo.getPages());
        List<TrainCarriageQueryResult> trainCarriageQueryList = BeanUtil.copyToList(trainCarriageList, TrainCarriageQueryResult.class);
        PageResult<TrainCarriageQueryResult> pageResult = new PageResult<>();
        pageResult.setTotal(trainCarriagePageInfo.getTotal());
        pageResult.setList(trainCarriageQueryList);
        return pageResult;
    }

    public void delete(Long id) {
        trainCarriageMapper.deleteByPrimaryKey(id);
    }

    public List<TrainCarriage> selectByTrainCode(String trainCode) {
        TrainCarriageExample trainCarriageExample = new TrainCarriageExample();
        trainCarriageExample.setOrderByClause("`index` asc");
        TrainCarriageExample.Criteria criteria = trainCarriageExample.createCriteria();
        criteria.andTrainCodeEqualTo(trainCode);
        return trainCarriageMapper.selectByExample(trainCarriageExample);
    }
}
